package com.example.ffepeg.ffpeg;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class VideoBackgroundMusic {
    //为视频添加背景音乐
    public static String addBackgroundMusic(String inputVideoPath, String inputMusicPath, String outputPath) throws IOException {
        String ffmpegCommand = "ffmpeg -i " + inputVideoPath + " -i " + inputMusicPath + " -c:v copy -c:a aac -b:a 192k -shortest " + outputPath;

        Runtime runtime = Runtime.getRuntime();
        Process process = runtime.exec(ffmpegCommand);

        BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
        String line;
        while ((line = errorReader.readLine()) != null) {
            System.out.println("ffmpeg error: " + line);
        }
        try {
            process.waitFor();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        return "123";
    }

    public static void main(String[] args) {
        // 视频文件路径
        String inputVideoPath = "D:\\javaXM\\FFEpeg\\src\\main\\resources\\out\\imgMP4out.mp4";
        // 背景音乐文件路径
        String inputMusicPath = "https://cdn1.suno.ai/15487e4b-7f29-4466-aa74-eb89be285244.mp3";
        // 输出文件路径
        String outputPath = "D:\\javaXM\\FFEpeg\\src\\main\\resources\\out\\outputWithMusic.mp4";
        try {
            String string = addBackgroundMusic(inputVideoPath, inputMusicPath, outputPath);
            System.err.println(string);
            System.out.println("Background music added successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
